package core.rendering;

import java.awt.Image;

import core.ImageLibrary;

public class AnimagedImage {

	Image imageStrip;
	Image frames[];

	private int width;
	private int height;
	private int cursor;
	private int frameTime;
	private long previousTime = Long.MIN_VALUE;
	
	public AnimagedImage(Image imageStrip_, int imgWidth, int imgHeight) {
		imageStrip = imageStrip_;
		width = imgWidth;
		height = imgHeight;
		generateFrames();
		cursor = 0;
		frameTime = 300;
	}

	private void generateFrames() {

		int numFrames = imageStrip.getWidth(null) / width;
		numFrames *= imageStrip.getHeight(null) / height;
		frames = new Image[numFrames];
		for (int currentFrame = 0; currentFrame < numFrames; currentFrame++) {
			frames[currentFrame] = ImageLibrary.getInstance().createEmptyImage(width, height);
			
			int destx1 = 0;
			int desty1 = 0;
			int destx2 = width;
			int desty2 = height;
			int sourcex1 = (currentFrame % numFrames) * width;
			int sourcey1 = 0;
			int sourcex2 = width + (currentFrame % numFrames) * width;
			int sourcey2 = height;
			frames[currentFrame].getGraphics().drawImage(imageStrip, destx1, desty1, destx2, desty2, sourcex1, sourcey1, sourcex2, sourcey2, null);
		}
	}

	public Image getNextFrame() {
		Image ret = frames[cursor];
		long currentTime = System.currentTimeMillis();
		if ((currentTime - previousTime) > frameTime){
			cursor ++;
			cursor %= frames.length;
		}
		return ret;	
	}
	
	public int getWidth(){
		return width;
	}
	public int getHeight(){
		return height;
	}
	
	

}
